local cjson = require "cjson"
local stats = ngx.shared.stats

-- 读取日志文件
local history = {}
local log_file = io.open("/usr/local/openresty/nginx/logs/stats.log", "r")
if log_file then
    for line in log_file:lines() do
        local time, count = line:match("([^|]+)|(%d+)")
        if time and count then
            table.insert(history, {time = time, count = tonumber(count)})
        end
    end
    log_file:close()
end

-- 获取当前分钟统计
local current_minute = stats:get("current_minute_key") or ""
local current_count = stats:get("current_minute_count") or 0

-- 确保 history 编码为数组
cjson.encode_empty_table_as_object(false)

local result = {
    current_minute = current_minute,
    current_count = current_count,
    history = history
}

ngx.header.content_type = "application/json"
ngx.say(cjson.encode(result))
